//
//  CarnivalsCategoriesTableDataViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 3/12/12.
//  Copyright 2012 Muludiang. All rights reserved.
//

#import "CarnivalsCategoriesTableDataViewController.h"
#import "PartyAnimalAppDelegate.h"
#import "CarnivalsSubCategoriesTableDataViewController.h"
#import "CarnivalsDetailViewController.h"
#import "iBacchanal.h"

@implementation CarnivalsCategoriesTableDataViewController

@synthesize carnivalsCategoriesTable;
@synthesize carnivalsCategoriesTableData;
@synthesize carnivalsSubCategoriesTableDataViewController;
@synthesize carnivalsDetailViewController;
@synthesize contentView;

-(void)getTableData{
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];			 
	
	carnivalsCategoriesTableData= [[NSMutableArray alloc] init];
	NSMutableArray *temp = [[NSMutableArray alloc] init];
	//NSLog(@"xxx: %@", bacchanal.carnivalsData);
	
	for (NSDictionary *carnival in bacchanal.carnivalsData)
	{
		NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
		[dateFormat setDateFormat:@"yyyy-MM-dd"];
		NSDate *tempdate = [dateFormat dateFromString:[carnival objectForKey:@"startDate"]];
		[dateFormat setDateFormat:@"yyyy"];
		NSString *tempStrDate = [dateFormat stringFromDate:tempdate];
		
		if ([bacchanal.selectedView isEqualToString: @"Years"]){
			
			if ([tempStrDate isEqualToString: bacchanal.selectedYear])
			{
				[dateFormat setDateFormat:@"yyyy-MM"];				
				//[temp addObject:[dateFormat stringFromDate:tempdate]];
				[temp addObject:[[NSDictionary alloc] initWithObjectsAndKeys:
								 [dateFormat stringFromDate:tempdate], @"startDate", nil]];
								//[carnival objectForKey:@"carnivals_id"], @"carnivalID", nil] ];
			}
		}
		else{
			if ([[carnival objectForKey:@"city"] isEqualToString: bacchanal.selectedCity])
			{
				[temp addObject:[NSDictionary dictionaryWithObjectsAndKeys:
								 [carnival objectForKey:@"startDate"], @"startDate",
								[carnival objectForKey:@"carnivals_id"], @"carnivalID", nil]];
				//[temp addObject:[carnival objectForKey:@"startDate"]];
			}
			
			
		}
		//NSLog(@"??:%@", temp);
		[dateFormat release];
	
	}

	temp = [[[NSSet setWithArray:temp] allObjects] retain] ;
	
	NSSortDescriptor *dateSort = [[[NSSortDescriptor alloc] initWithKey:@"startDate" ascending:YES selector:@selector(compare:)] autorelease	];
	NSArray *descriptors = [NSArray arrayWithObjects:dateSort, nil];
	//carnivalsSubCategoriesTableData = [[temp sortedArrayUsingDescriptors:descriptors ] retain];

	
	carnivalsCategoriesTableData = [[temp sortedArrayUsingDescriptors:descriptors ] retain];
	//[[[[NSSet setWithArray:temp] allObjects] sortedArrayUsingSelector:@selector(compare:)]retain] ;
	[temp release];
}

// Helper functions to get height of banner
- (int)getBannerHeight:(UIDeviceOrientation)orientation {
    if (UIInterfaceOrientationIsLandscape(orientation)) {
        return 32;
    } else {
        return 50;
    }
}

- (int)getBannerHeight {
    return [self getBannerHeight:[UIDevice currentDevice].orientation];
}

// Helper function to size views
- (void)fixupAdView:(UIInterfaceOrientation)toInterfaceOrientation {
 	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBannerView  != nil) {        
        if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
            [bacchanal.adBannerView  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierLandscape];
        } else {
            [bacchanal.adBannerView  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierPortrait];
        }          
        [UIView beginAnimations:@"fixupViews" context:nil];
        if (bacchanal.adBannerViewIsVisible) {
            CGRect adBannerViewFrame = [bacchanal.adBannerView  frame];
            adBannerViewFrame.origin.x = 0;
            adBannerViewFrame.origin.y = 0;
            [bacchanal.adBannerView  setFrame:adBannerViewFrame];
            CGRect contentViewFrame = contentView.frame;
            contentViewFrame.origin.y = [bacchanal getBannerHeight:toInterfaceOrientation];
            contentViewFrame.size.height = self.view.frame.size.height - [bacchanal getBannerHeight:toInterfaceOrientation];
            contentView.frame = contentViewFrame;
        } else {
			[self hideBanner:toInterfaceOrientation];
        }
        [UIView commitAnimations];
    }   
}

-(void)hideBanner:(UIInterfaceOrientation)toInterfaceOrientation{
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	CGRect adBannerViewFrame = [bacchanal.adBannerView frame];
	adBannerViewFrame.origin.x = 0;
	adBannerViewFrame.origin.y = - [bacchanal getBannerHeight:toInterfaceOrientation];
	[bacchanal.adBannerView  setFrame:adBannerViewFrame];
	CGRect contentViewFrame = contentView.frame;
	contentViewFrame.origin.y = 0;
	contentViewFrame.size.height = self.view.frame.size.height + [bacchanal getBannerHeight:toInterfaceOrientation];
	contentView.frame = contentViewFrame;            
 	
}

// Implement AdBannerViewDelegate
#pragma mark ADBannerViewDelegate

- (void)bannerViewDidLoadAd:(ADBannerView *)banner {
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (!bacchanal.adBannerViewIsVisible) {                
        bacchanal.adBannerViewIsVisible = YES;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBannerViewIsVisible)
    {        
        bacchanal.adBannerViewIsVisible = NO;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}
#pragma mark -
#pragma mark Initialization

/*
 - (id)initWithStyle:(UITableViewStyle)style {
 // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 self = [super initWithStyle:style];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	if (bacchanal.selectedCity != nil)		
	self.navigationItem.title = bacchanal.selectedCity;
	else
		self.navigationItem.title = bacchanal.selectedYear;
	
	[self getTableData];
	[carnivalsCategoriesTable reloadData];
	carnivalsCategoriesTable.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"iBacchanalbkgd.png"]];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	//[self createAdBannerView];
	
        
	
}


 - (void)viewWillAppear:(BOOL)animated {
 [super viewWillAppear:animated];
	 iBacchanal *bacchanal = [iBacchanal sharedUser];
[self.view addSubview:bacchanal.adBannerView];
 [self fixupAdView:[UIDevice currentDevice].orientation];
 }
 
 -(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
 [self fixupAdView:toInterfaceOrientation];
 }

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */

 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
	 iBacchanal *bacchanal = [iBacchanal sharedUser];
	 [bacchanal.adBannerView removeFromSuperview];
 
 	 
 }
 
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.carnivalsCategoriesTableData count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	
	iBacchanal* bacchanal = [iBacchanal sharedUser];
	
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	NSDate *tempdate;
	if ([bacchanal.selectedView isEqualToString: @"Years"]){
		[dateFormat setDateFormat:@"yyyy-MM"];
		tempdate = [dateFormat dateFromString:[[carnivalsCategoriesTableData objectAtIndex:indexPath.row] objectForKey:@"startDate"]];
		[dateFormat setDateFormat:@"MMMM"];
		[[cell textLabel] setText:[dateFormat stringFromDate:tempdate]];
	}
	else{
		[dateFormat setDateFormat:@"yyyy-MM-dd"];
		tempdate = [dateFormat dateFromString:[[carnivalsCategoriesTableData objectAtIndex:indexPath.row] objectForKey:@"startDate"]];
		[dateFormat setDateFormat:@"MMMM dd, YYYY"];
		[[cell textLabel] setText:[dateFormat stringFromDate:tempdate]];
	}
	
	[dateFormat release];
	return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	/*NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)] invertedSet];
	 NSString *trimmed = [[cell textLabel].text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
	 BOOL isNumeric = trimmed.length > 0 && [trimmed rangeOfCharacterFromSet:nonNumberSet].location == NSNotFound;
	 NSString *temp = [NSString stringWithFormat:@"%@ (Done)",[cell textLabel].text ];
	 */
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	/*if ((isNumeric) && [[cell textLabel].text intValue] < 2012){
	 [[cell textLabel] setTextColor:[UIColor redColor]];
	 [[cell textLabel] setText:temp];	
	 }
	 else{
	 [[cell textLabel] setTextColor:[UIColor blackColor]];
	 }*/
	
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	if ([bacchanal.selectedView isEqualToString: @"Years"]){
		CarnivalsSubCategoriesTableDataViewController *carnivalsSubCategoriesTableDataView = [[CarnivalsSubCategoriesTableDataViewController alloc] initWithNibName:@"CarnivalsSubCategoriesTable" bundle:nil];
		self.carnivalsSubCategoriesTableDataViewController = carnivalsSubCategoriesTableDataView;
		
		bacchanal.selectedYearMonth = [[carnivalsCategoriesTableData objectAtIndex:indexPath.row] objectForKey:@"startDate"];		[self.navigationController pushViewController:carnivalsSubCategoriesTableDataView animated:YES];
		[carnivalsSubCategoriesTableDataView release];
		
		
	}
	else{
		CarnivalsDetailViewController *carnivalsDetailView = [[CarnivalsDetailViewController alloc] initWithNibName:@"CarnivalsDetail" bundle:nil];
		self.carnivalsDetailViewController = carnivalsDetailView;
		bacchanal.carnivalDate = [[carnivalsCategoriesTableData objectAtIndex:indexPath.row] objectForKey:@"startDate"];
		bacchanal.carnivalID = [[carnivalsCategoriesTableData objectAtIndex:indexPath.row] objectForKey:@"carnivalID"];
		[self.navigationController pushViewController:carnivalsDetailView animated:YES];
		[carnivalsDetailView release];
		
	}
	
	//Reuse NavController
	PartyAnimalAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.partyAnimalNavigatorViewController pushViewController:carnivalsSubCategoriesTableDataViewController animated:YES];
	
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[contentView release];
	[carnivalsDetailViewController release];
	[carnivalsSubCategoriesTableDataViewController release];
	[carnivalsCategoriesTableData release];
	[carnivalsCategoriesTable release];
    [super dealloc];
}


@end

